package com.canbot.u05.versionupdate

import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast
import com.canbot.u05.versionupdate.utils.AppUtils

/**
 * @author yinxiaowei
 * @date 2020/7/30
 * @description:
 */
object VersionCheckMgr {
    private var getSelfCheckUpdateResult = false

    private var selfHasNewVersion = false

    private var selfCheckUpdateFailed = false
    private const val TAG = "VersionCheckMgr"
    private lateinit var context: Context

    private var aboutHintDialog: AboutHintDialog? = null
    private fun showDialog() {
        Handler(Looper.getMainLooper()).post {
            aboutHintDialog = AboutHintDialog(context, 2, context.getString(R.string.dialog_loading))
            aboutHintDialog?.let {
                it.show()
                it.setDialogWindowAttr(context.resources.getDimension(R.dimen.x588),
                        context.resources.getDimension(R.dimen.x340))
            }
        }
    }

    private fun cancelDialog() {
        aboutHintDialog?.let {
            it.cancel()
        }
    }

    /**
     * 版本更新检测
     */
    fun checkNewVersion(context: Context, branchName: String, versionCode: Int, padMac: String, headMac: String, isShow: Boolean) {
        this.context = context
        UpdateConfig.BRANCH_NAME = branchName
        UpdateConfig.VERSION_CODE = versionCode
        UpdateConfig.PAD_MAC = padMac.replace(":", "")
        UpdateConfig.HEAD_MAC = headMac.replace(":", "")


        if (UpdateConfig.isCancelAutoCheckNewVersion) {
            Log.e(TAG, "已关闭自动检测版本更新")
            return
        }
        // 版本更新检测
        if (isShow) {
            showDialog()
        }
        VersionUpdateUtils.getInstance(context).let {
            it.isHasNewVersion(object : VersionUpdateUtils.VersionUpdateCallback() {
                override fun isHasNewVersion(isHas: Boolean, enabledUpdate: Boolean) {
                    cancelDialog()
                    getSelfCheckUpdateResult = true
                    if (enabledUpdate.not()) {
                        selfHasNewVersion = false
                        return
                    } else {
                        selfHasNewVersion = isHas
                    }
                    notifyCheckUpdateResult(isShow)
                    Log.e(TAG, "是否开启版本更新：${enabledUpdate}，胸口 ${(if (isHas) "有" else "无") + "新版本"}")
                }

                override fun onFailure(msg: String, enableUpdate: Boolean) {
                    cancelDialog()
                    getSelfCheckUpdateResult = true
                    selfCheckUpdateFailed = true
                    notifyCheckUpdateResult(isShow)
                }
            })
        }
    }

    /**
     * 同时获取到头部及胸口检查结果再处理
     */
    private fun notifyCheckUpdateResult(show: Boolean) {
        if (getSelfCheckUpdateResult) {
            when {
                selfHasNewVersion -> {
                    // 已经进入更新了，不再弹窗
                    if (UpdateActivity::class.java.name == AppUtils.getTopActivityName(context)) {
                        return
                    }

                    val intent = Intent(context, UpdateActivity::class.java).apply {
                        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        val selfUpdateStatue = if (selfHasNewVersion) 1 else if (selfCheckUpdateFailed) 0 else -1
                        putExtra(UpdateActivity.CHECK_SELF_UPDATE_STATUS, selfUpdateStatue)
                    }
                    Handler(Looper.getMainLooper()).post {
                        VersionUpdateUtils.getInstance(context).showUpdateSelectDialog(intent)
                    }
                }
                selfCheckUpdateFailed -> {
                    Log.e(TAG, "检测失败，请检查网络后尝试")
                    if (show) {
                        Handler(Looper.getMainLooper()).post {
                            Toast.makeText(context, "检测失败", Toast.LENGTH_SHORT).show()
                        }
                    }

                }
                else -> {
                    Log.i(TAG, "notifyCheckUpdateResult: 没有新版本......")
                    if (show) {
                        Handler(Looper.getMainLooper()).post {
                            Toast.makeText(context, "已经是最新版本", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }
        }
    }
}